package mdb

import (
	"fmt"
	"gitee.com/dennis-mxx/mxx-core-v2/menv"
	"gitee.com/dennis-mxx/mxx-core-v2/mexception"
	"gitee.com/dennis-mxx/mxx-core-v2/mlogger"
	_ "github.com/go-sql-driver/mysql"
	"strings"
	"time"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
)

func InitMysql(dataSource *menv.Mysql) {
	if dataSource.Addr == "" {
		panic(mexception.NewException(mexception.NilException, "mysql.addr is nil"))
	}

	if dataSource.MaxIdleConn == 0 {
		dataSource.MaxIdleConn = 5
	}
	if dataSource.MaxOpenConn == 0 {
		dataSource.MaxOpenConn = 600
	}
	if dataSource.Timeout == 0 {
		dataSource.Timeout = 30
	}
	var addr string
	if i := strings.Index(dataSource.Addr, "@"); i >= 0 {
		addr = "user:pass" + dataSource.Addr[i:]

	} else {
		addr = dataSource.Addr
	}
	if engine, err := ConnectionMysql(dataSource); err == nil {
		Engine = engine
		mlogger.Out.Info(fmt.Sprintf("Initialize [Connection mysql database [%s/%s] successful] ", dataSource.Addr, addr))
	} else {
		panic(fmt.Sprintf("connection mysql database [%s] failure ", addr))
	}
}

func ConnectionMysql(dataSource *menv.Mysql) (*xorm.Engine, error) {
	defer mlogger.FormatException()

	engine, err := xorm.NewEngine("mysql", dataSource.Addr)
	if err == nil {
		timeout := time.Duration(dataSource.Timeout)
		engine.SetMaxOpenConns(dataSource.MaxOpenConn)        // 用于设置最大打开的连接数，默认值为0表示不限制
		engine.SetMaxIdleConns(dataSource.MaxIdleConn)        // 用于设置闲置的连接数
		engine.SetConnMaxLifetime(timeout * time.Millisecond) // 设置一个超时时间，时间小于数据库的超时时间即可
		engine.SetLogger(&ZapXormLogger{})
		engine.ShowSQL(dataSource.ShowSql)
		engine.EnableSessionID(true)
		if menv.Environment.Logger != nil && menv.Environment.Logger.Level != "" {
			if strings.EqualFold(menv.Environment.Logger.Level, "warning") {
				engine.SetLogLevel(log.LOG_WARNING)
			} else if strings.EqualFold(menv.Environment.Logger.Level, "error") {
				engine.SetLogLevel(log.LOG_ERR)
			} else if strings.EqualFold(menv.Environment.Logger.Level, "debug") {
				engine.SetLogLevel(log.LOG_DEBUG)
			} else {
				engine.SetLogLevel(log.LOG_INFO)
			}

		}

	}

	return engine, err
}
